const videoUtils = require("../../utils/videoUtils");

// pages/videoTest/videoTest.js
const app = getApp()
Page({
  data: {
      cover:"cover",
      videoId:"",
      src:"",
      videoInfo:{},

      userLikeVideo:false,

      commentsPage:1,
      commentsTotalPage:1,
      commentsList:[],

      placeholder:"说点什么..."
  },

  videoCtx:{},

  onLoad:function(params){
    var me = this;
    me.videoCtx = wx.createVideoContext('myVideo', me);  
    //获取上一个页面传入的参数;
    var videoInfo = JSON.parse(params.videoInfo);
    
    var height = videoInfo.videoHeight;
    var width = videoInfo.width;
    var cover = "cover";
    if(width>=height){
      cover="";
    }
    me.setData({
      videoId: videoInfo.id,
      src: app.serverUrl + videoInfo.videoPath,
      videoInfo: videoInfo,
      cover: cover
    })
    var serverUrl = app.serverUrl;
    var user = app.getGlobalUserInfo();
    var loginUserId = "";
    if(user != null || user != undefined || user != ''){
      loginUserId = user.id;
    }
    wx.request({
      //获取当前登录用户与视频发布者的关系
      url: serverUrl + '/user/getPublisher.do?loginUserId=' + loginUserId + "&videoId=" + videoInfo.id + "&publishUserId=" + videoInfo.userId ,
      method: "POST",
      success:function(res){
        console.log(res.data);

        var publisher = res.data.data.publisher;
        var userLikeVideo = res.data.data.userLikeVideo;

        me.setData({
          serverUrl: serverUrl,
          publisher: publisher,
          userLikeVideo: userLikeVideo
        });
      }
    })
    me.getCommentsList(1);
  },

  onShow:function(){
    var me = this;
    me.videoCtx.play();
  },

  onHide:function(){
    var me = this;
    me.videoCtx.pause();
  },

  upload:function(){
    var me = this;
    var user = app.getGlobalUserInfo();
    var videoInfo = JSON.stringify(me.data.videoInfo);
    var realUrl = '../videoInfo/videoInfo#videoInfo@' + videoInfo;
    if(user == null || user == undefined || user == '' ){
      wx.navigateTo({
        url: '../userLogin/login?redirectUrl=' + realUrl,
      })
    } else{
        videoUtils.uploadVideo();
      }
  },

  showSearch:function(e){
    wx.navigateTo({
      url: '../searchVideo/searchVideo',
    })
  },
  
  showPublisher:function(){
    var me = this;
    var user = app.getGlobalUserInfo();
    var videoInfo = me.data.videoInfo;
    var realUrl = '../mine/mine#publisherId@' + videoInfo.userId;

    if(user == null || user == undefined || user==''){
      wx.navigateTo({
        url: '../userLogin/login?redirectUrl='+realUrl,
      })
    }else{
      wx.navigateTo({
        url: '../mine/mine?publisherId='+videoInfo.userId,
      })
    }
  },

  showMine:function(){
    var user = app.getGlobalUserInfo();
    if(user == null || user == undefined || user == ''){
      wx.navigateTo({
        url: '../userLogin/login',
      })
    }else{
      wx.navigateTo({
        url: '../mine/mine',
      })
    }
  },

  showIndex:function(){
    wx.redirectTo({
      url: '../index/index',
    })
  },

  // fixme：用户可以给一个视频重复点赞...
  likeVideoOrNot:function(){
    var me = this;
    var videoInfo = me.data.videoInfo;
    var user = app.getGlobalUserInfo();
    if (user == null || user == undefined || user == '') {
      wx.navigateTo({
        url: '../userLogin/login',
      })
    } else {
      var userLikeVideo = me.data.userLikeVideo;
      var url = '/video/userLike.do?userId=' + user.id + '&videoId=' + videoInfo.id + 
      '&videoCreaterId=' + videoInfo.userId;
      if(userLikeVideo){
        url = '/video/userUnLike.do?userId=' + user.id + '&videoId=' + videoInfo.id + 
      '&videoCreaterId=' + videoInfo.userId;
      }
      var serverUrl = app.serverUrl;
      wx.showLoading({
        title: '少女祈祷中...',
      })
      wx.request({
        url: serverUrl + url,
        method: 'POST',
        header:{
          'content-type': 'application/json', // 默认值
          'headerUserId': user.id,
          'headerUserToken': user.userToken
        },
        success:function(res){
          wx.hideLoading();
          me.setData({
            userLikeVideo: !userLikeVideo
          });
        }
      })
    }
  },

  shareMe:function(){
    var me = this;
    var user = app.getGlobalUserInfo();
    wx.showActionSheet({
      itemList: ['下载到本地','举报用户','分享到朋友圈', '分享到QQ空间', '分享到微博'],
      success:function(res){
        console.log(res.tapIndex);
        //todo 需手机端测试...
        if(res.tapIndex == 0){
          //下载
          wx.showLoading({
            title: '下载中...',
          })
          wx.downloadFile({
            url: app.serverUrl + me.data.videoId.videoPath,
            success:function(res){
              //只要服务器有响应数据，就会把响应数据写入文件success 回调，业务需要自行判断是否下载到了想要的内容
              if(res.statusCode === 200){
                console.log(res.tempFilePath);
                wx.saveVideoToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success:function(res){
                    console.log(res.errMsg);
                    wx.hideLoading();
                  }
                })
              }
            }
          })
        }
        else if(res.tapIndex == 1){
          //举报
          var videoInfo = JSON.stringify(me.data.videoInfo);
          var realUrl = '../videoInfo/videoInfo#videoInfo@' + videoInfo;

          if(user == null || user == undefined || user == '' ){
            wx.navigateTo({
              url: '../userLogin/login?redirectUrl=' + realUrl,
            })
          } else {
            var publishUserId = me.data.videoInfo.userId;
            var videoId = me.data.videoInfo.id;
            var currentUserId = user.id;
            wx.navigateTo({
              url: '../report/report?videoId=' + videoId + '&publishUserId=' + publishUserId,
            })
          }
        }
        else{
          wx.showToast({
            title: '官方尚未开发...',
            icon: 'none',
            duration: 3000
          })
        }
      }
    })
  },

  leaveComment:function(){
    //获取评论区焦点功能
    this.setData({
      commentFocus: true
    })
  },

  saveComment:function(e){
    var me = this;
    var content = e.detail.value;

    //获取评论回复的fatherCommentId 与 toUserId
    var fatherCommentId = e.currentTarget.dataset.replyfathercommentid;
    var toUserId = e.currentTarget.dataset.replytouserid;

    var user = app.getGlobalUserInfo();
    var videoInfo = JSON.stringify(me.data.videoInfo);
    var realUrl = '../videoInfo/videoInfo#videoInfo@' + videoInfo;
    var serverUrl = app.serverUrl;
    if(user == null || user == undefined || user == '' ){
      wx.navigateTo({
        url: '../userLogin/login?redirectUrl=' + realUrl,
      })
    } else {
      wx.showLoading({
        title: '少女祈祷中...',
      }),
      wx.request({
        url: serverUrl + '/video/saveComment.do?fatherCommentId=' + fatherCommentId + '&toUserId=' + toUserId,
        method: 'POST',
        header:{
          'content-type': 'application/json', // 默认值
          'headerUserId': user.id,
          'headerUserToken': user.userToken
        },
        data:{
          fromUserId: user.id,
          videoId: me.data.videoInfo.id,
          comment: content
        },
        success:function(res){
          console.log(res),
          wx.hideLoading(),
          me.setData({
            contentValue: "",
            commentsList:[]
          }),
          me.getCommentsList(1)
        }
      })
    }
  },
  // commentsPage:1,
  // commentsTotalPage:1,
  // commentsList:[],
  getCommentsList:function(page){
    var me = this;
    var videoId = me.data.videoInfo.id;
    var serverUrl = app.serverUrl;
    var user = app.getGlobalUserInfo();
    wx.request({
      url: serverUrl + "/video/getAllComments.do?videoId=" + videoId + "&page=" + page,
      method: 'POST',
      header:{
        'content-type': 'application/json', // 默认值
        'headerUserId': user.id,
        'headerUserToken': user.userToken
      },
      success:function(res){
        console.log(res.data);
        var commentsList = res.data.rows;
        var newCommentsList = me.data.commentsList;
        me.setData({
          commentsList: newCommentsList.concat(commentsList),
          commentsPage: page,
          commentsTotalPage: res.data.total
        })
      }
    })
  },

  replyFocus:function(e){
    var fatherCommentId = e.currentTarget.dataset.fathercommentid;
    var toUserId = e.currentTarget.dataset.touserid;
    var toNickname = e.currentTarget.dataset.tonickname;

    this.setData({
      placeholder: "回复" + toNickname,
      replyFatherCommentId: fatherCommentId,
      replyToUserId: toUserId,
      commentFocus: true
    })
  },

  onReachBottom:function(){
    var me = this;
    var currentPage = me.data.commentsPage;
    var totalPage = me.data.commentsTotalPage;
    if(currentPage == totalPage){
      return;
    }
    var page = currentPage + 1 ;
    me.getCommentsList(page);
  }




})